﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using KewlStuff.Extensions;
using MovieModel.Search;

namespace MovieModel.Model.Common
{
    [ContractClass(typeof(MovieItemContracts))]
    public abstract class MovieItem
    {
        public int Id { get; internal set; }
        public string Name { get; internal set; }
        public abstract bool Matches(SearchQuery query);

        public override string ToString()
        {
            return Name;
        }
    }

    [ContractClassFor(typeof(MovieItem))]
    public abstract class MovieItemContracts : MovieItem
    {
        public override bool Matches(SearchQuery query)
        {
            Contract.Requires(query != null);
            throw new NotImplementedException();
        }
    }

    public abstract class MovieItem<T> : MovieItem where T : MovieItem<T>, new()
    {
        public IEnumerable<string> SearchMatches { get; internal set; }
        public event EventHandler<ItemUpdatedEventArgs<MovieItem<T>>> ItemUpdated;

        protected void InvokeItemUpdated()
        {
            var handler = ItemUpdated;
            if (handler != null) handler(this, new ItemUpdatedEventArgs<MovieItem<T>>(this));
        }

        /// <summary>
        /// Checks items contained in this movie item for matches
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        protected abstract bool SubMatches(SearchQuery query);
        public override bool Matches(SearchQuery query)
        {
            if (query.Free != null)
            {
                foreach (string f in query.Free)
                {
                    string free = f;
                    if (Name.ContainsIgnoreCase(free)) return true;
                    if (SearchMatches != null && SearchMatches.Any(sm => sm.ContainsIgnoreCase(free))) return true;
                }
            }
            return SubMatches(query);
        }

    }
}
